package com.tea.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.tea.Model.User;
import com.tea.Model.dto.LoginDTO;
import com.tea.utils.JwtUtils;
import com.tea.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
@Slf4j
public class LoginService {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;

    public Result<String> login(LoginDTO code) {
        try {
            // 通过 code 换取 session_key 和 openid
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code.getCode());
            log.info("微信登录响应: {}", sessionResult);
            String openid = sessionResult.getOpenid();
            
            // 检查用户是否已存在，如果不存在则创建新用户
            User existingUser = userService.getUserByOpenId(openid);
            if (existingUser == null) {
                // 创建新用户
                User newUser = new User();
            newUser.setOpenId(openid);
            newUser.setRole(0); // 默认为普通用户
            newUser.setStatus(1); // 启用状态
            newUser.setDeleted(0); // 未删除
            newUser.setCreateTime(LocalDateTime.now());
            newUser.setUpdateTime(LocalDateTime.now());
                
                boolean saved = userService.save(newUser);
                if (saved) {
                    log.info("新用户创建成功，openid: {}", openid);
                } else {
                    log.error("新用户创建失败，openid: {}", openid);
                }
            } else {
                // 更新现有用户的登录时间
                existingUser.setUpdateTime(LocalDateTime.now());
                userService.updateById(existingUser);
                log.info("用户登录成功，openid: {}", openid);
            }
            
            String token = jwtUtils.generateToken(openid);
            return Result.success(token);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("无效的登录code");
        }
    }
}